<?php
namespace app\common\service;

use app\admin\Service;
use app\common\model\AppleDebtBacked;
use app\common\model\AppleRepayPlan;
use app\common\model\OppoOrder;

class PlanService extends Service
{
    public static function overdue()
    {
        //状态待归还  过了还款日
        $date = date('Y-m-d');
        $planLst = AppleRepayPlan::where(['status' => 0, 'refund_sts' => 0])->where('plan_date', '<', $date)->update(['status' => 2, 'have_overdue' => 1]);

        //违约金数组
        $singleArr = [];
        $monthAgo = date('Y-m-d', strtotime('-1 month'));
        //状态已逾期
        $lst = AppleRepayPlan::where(['status' => 2])->where('plan_date', '>', $monthAgo)->select();
        if(!empty($lst)){
            foreach ($lst as $v){
                //单日违约金
                if(in_array($v['order_id'], $singleArr)){
                    $single = $singleArr[$v['order_id']];
                }else{
                    $order = OppoOrder::where('order_id' , $v['order_id'])->field('id, sign_price')->find();
                    //已还款金额
                    $pay = AppleDebtBacked::where(['order_id' => $v['order_id'], 'bill_type' => 1])->sum('payment_amount');
                    $single = number_format(($order['sign_price'] - $pay) / 1000, 2);
                    $singleArr[$v['order_id']] = $single;
                }
                //违约天数
                //下一期账单日
                $next_index = $v['plan_index'] + 1;
                $next = AppleRepayPlan::where(['order_id' => $v['order_id'], 'plan_index' => $next_index])->find();
                if(empty($next)){
                    continue;
                }else{
                    //超出下期账单日
                    if($date >= $next['plan_date']){
                        $last = $next['plan_date'];
                    }else{
                        //未到下期账单日
                        $last = $date;
                    }
                    //相差天数
                    $diff = (strtotime($last) - strtotime($v['plan_date'])) / 86400;
                }
                $v->overdue_day = $diff;
                $v->overdue_fine = $v->overdue_fine + $single;
                $v->plan_total_amount = $v->plan_amount + $v->overdue_fine;
                $v->save();
            }
        }

        echo '完成';
    }
}